package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusRequest;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.ElderlyPerson;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 老人家属Service业务层处理
 *
 * @author alexis
 * @date 2025-01-09
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RoomTypeMapper roomTypeMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private IFamilyMemberElderService familyMemberElderService;

    @Autowired
    private IDeviceService deviceService;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );



    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 小程序登录方法
     *
     * @param userLoginRequestDto 请求数据
     * @return 登录结果，包含token和nickname
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1.调用微信官方接口获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());

        // 2.根据openId查询数据库获取用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));

        // 3.如果用户信息不存在，就创建一个用户，并绑定openId
        if (ObjectUtils.isEmpty(familyMember)) {
            // 新用户
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }

        // 4.调用微信接口获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        // 不论是新用户还是老用户，都更新手机号
        familyMember.setPhone(phoneNumber);

        // 5.保存或更新用户，如果是新增，要生成一个用户名
        saveOrUpdateFamilyMember(familyMember);

        // 6.封装用户信息到token中，返回给小程序
        LoginVo loginVo = new LoginVo();
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        // 返回结果
        return loginVo;
    }

    //绑定老人家属
    @Override
    public void add(ElderlyPerson elderlyPerson) {
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, elderlyPerson.getIdCard()).eq(Elder::getName, elderlyPerson.getName()));
        if (ObjectUtil.isNotEmpty(elder)) {
            Long l = UserThreadLocal.get();
            Long id = elder.getId();
            String remark = elderlyPerson.getRemark();
            FamilyMemberElder familyMemberElder = new FamilyMemberElder();
            familyMemberElder.setFamilyMemberId(l);
            familyMemberElder.setElderId(id);
            familyMemberElder.setRemark(remark);
            familyMemberElderService.save(familyMemberElder);
        }
        else {
            throw new RuntimeException("该老人不存在");
        }
    }

    @Override
    public List<ElderlyFamilyMemberVO> getMyelderlyPersonList() {
        Long l = UserThreadLocal.get();
        List<FamilyMemberElder> list = familyMemberElderService.list(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, l));
        if (ObjectUtil.isEmpty(list)) {
            return null;
        }
        ArrayList<ElderlyFamilyMemberVO> bean = new ArrayList<>();
        list.forEach(item -> {
            ElderlyFamilyMemberVO s = BeanUtil.toBean(item, ElderlyFamilyMemberVO.class);
            bean.add(s);
        });
        Long elderId = list.get(0).getElderId();
        Elder elder = elderMapper.selectById(elderId);
        String name = elder.getName();
        bean.forEach(item -> {
            item.setElderName(name);
        });
        return bean;
    }

    @Override
    public List<ElderlyFamilyMemberRoomVO> listByPage(int pageNum, int pageSize) {
        List<FamilyMemberElder> list = familyMemberElderService.list();
        List<ElderlyFamilyMemberRoomVO> elderlyFamilyMemberRoomVOS = new ArrayList<>();
        list.forEach(item -> {
            ElderlyFamilyMemberRoomVO elderlyFamilyMemberRoomVO = new ElderlyFamilyMemberRoomVO();
            elderlyFamilyMemberRoomVO.setMid(item.getFamilyMemberId());
            elderlyFamilyMemberRoomVO.setMremark(item.getRemark());
            elderlyFamilyMemberRoomVO.setElderId(item.getElderId());
            Elder elder = elderMapper.selectElderById(item.getElderId());
            elderlyFamilyMemberRoomVO.setName(elder.getName());
            elderlyFamilyMemberRoomVO.setImage(elderMapper.selectElderById(item.getElderId()).getImage());
            elderlyFamilyMemberRoomVO.setBedNumber(elderMapper.selectElderById(item.getElderId()).getBedNumber());
            Long bedId = elderMapper.selectElderById(item.getElderId()).getBedId();

            Long roomId = bedMapper.selectBedById(bedId).getRoomId();
            String typeName = roomMapper.selectRoomById(roomId).getTypeName();
            String name = roomTypeMapper.selectOne(Wrappers.<RoomType>lambdaQuery().eq(RoomType::getName, typeName)).getName();
            elderlyFamilyMemberRoomVO.setTypeName(name);

            Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getBindingLocation, item.getElderId().toString()));
            if (ObjectUtil.isNotEmpty(device)) {
                elderlyFamilyMemberRoomVO.setDeviceName(device.getDeviceName());
                elderlyFamilyMemberRoomVO.setIotId(device.getIotId());
                elderlyFamilyMemberRoomVO.setProductKey(device.getProductKey());
            }else {
                elderlyFamilyMemberRoomVO.setIotId(null);
                elderlyFamilyMemberRoomVO.setDeviceName(null);
                elderlyFamilyMemberRoomVO.setProductKey(null);
            }

            elderlyFamilyMemberRoomVOS.add(elderlyFamilyMemberRoomVO);
        });

        return elderlyFamilyMemberRoomVOS;
    }

    @Override
    public AjaxResult QueryDevicePropertyStatus(Device device) {
        QueryDevicePropertyStatusRequest request = new QueryDevicePropertyStatusRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setProductKey(device.getProductKey());
        request.setDeviceName(device.getDeviceName());
        AjaxResult ajaxResult = deviceService.queryDevicePropertyStatus(request);
        return ajaxResult;
    }

    @Override
    public DataVo queryDeviceDataListByDay(DeviceDataQuery deviceDataQuery) {

        return null;
    }

    /**
     * 新增或更新老人家属
     *
     * @param familyMember 老人家属对象
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {
        // 判断id是否为空
        if (ObjectUtils.isEmpty(familyMember.getId())) {
            // 新增
            // 生成一个随机的用户名，规则是：一个随机的好听的名字+手机号后4位
            String prefix = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()));
            String nickName = prefix + familyMember.getPhone().substring(7);
            familyMember.setName(nickName);
            familyMemberMapper.insert(familyMember);
        } else {
            // 更新
            familyMemberMapper.updateById(familyMember);
        }
    }
}
